package com.china08.yxyapi.rabbitmq.listener;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.china08.yxyapi.config.RabbitConfig;
import com.china08.yxyapi.entity.db.attendance.YxyYxyTecAttendanceConfig;
import com.china08.yxyapi.entity.db.yxy.YxyHoliday;
import com.china08.yxyapi.repository.db.attendance.YxyTecAttendanceConfigRepository;
import com.china08.yxyapi.repository.db.yxy.YxyHolidayRepository;
import com.china08.yxyapi.repository.mg.attendance.YxyTeaAttendanceRepository;
import com.china08.yxyapi.service.manage.edu.platform.statistics.impl.TeaAttendanceStatisticsService;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * 教师考勤统计
 *
 */
@Component
@EnableRabbit
public class TecAttendanceStatisticsListener {

    private static final Logger LOG = Logger.getLogger(TecAttendanceStatisticsListener.class);

    @Autowired
    private YxyTeaAttendanceRepository yxyTeaAttendanceRepository;

    @Value(value = "${yx.rest.api.yx.path}")
    private String yxyApiYxUrl;

    @Autowired
    private YxyTecAttendanceConfigRepository attendanceConfigRepository;

    @Autowired
    private TeaAttendanceStatisticsService teaAttendanceStatisticsService;

    @Autowired
    YxyHolidayRepository yxyHolidayRepository;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据学校ID 统计此学校的教师考勤,
     * 
     * 参数中 schoolIdAndDay , map中key 为schoolId value:为日期 20170411
     */
    @RabbitListener(queues = RabbitConfig.YW_TEA_ATTENDANCE_STATISTICS)
    private void attendanceStatistics(String schoolIdAndDay) {

        String[] schoolIdDay = schoolIdAndDay.split("_");
        if (schoolIdDay.length != 2) { return; } // 长度不为2, 直接跳出
        // schoolId 虽然为 Set 但是只有一条
        String schoolId = schoolIdDay[0];
        Integer day = Integer.parseInt(schoolIdDay[1]);
        // 先根据学校id和日期,查询打卡记录表中是否有此学校的打卡记录,只有有一条就可以
        if (yxyTeaAttendanceRepository.findTopByDayOfDateAndSchoolId(day, schoolId) == null) {
            // 一条记录都没有,不需要统计
            LOG.info("day: " + day + " schoolID: " + schoolId + " is not any teacher sign in ! ");
            return;
        }
        // 根据schoolId 获取本学校说有教师信息.

        try {
            ResponseEntity<List<TeaRespModel>> reList = restTemplate.exchange(
                    yxyApiYxUrl + "/comm/teacherofschool/schoolId/" + schoolId, HttpMethod.GET, null,
                    new ParameterizedTypeReference<List<TeaRespModel>>() {
                    });

            // 查询所有教师信息
            if (reList != null && reList.getBody() != null && reList.getBody().size() > 0) {
                // 有教师信息, 进行考勤统计
                List<YxyHoliday> holiday = yxyHolidayRepository
                        .findByYear(Integer.parseInt(StringUtils.substring(day + "", 0, 4)));
                YxyYxyTecAttendanceConfig aconfig = attendanceConfigRepository.findBySchoolId(schoolId);// 查询配置
                if (aconfig != null) {
                    for (TeaRespModel rm : reList.getBody()) {
                        teaAttendanceStatisticsService.switchTimes(
                                aconfig.getTimes(), rm, yxyTeaAttendanceRepository
                                        .findByDayOfDateAndTeacherIdOrderBySignTime(day, rm.getTeacherId()),
                                aconfig, day, holiday);
                    }
                }

            } else {
                LOG.info("schoolId: " + schoolId + " is not teacher information! ");
            }
        } catch (RestClientException e) {
            LOG.error("RestClientException: yxyApiYxUrl  /api_yx/comm/teacherofschool/schoolId/");
        }

    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class TeaRespModel {
        @JsonCreator
        public TeaRespModel(@JsonProperty("teacherId") String teacherId, @JsonProperty("schoolId") String schoolId,
                @JsonProperty("schoolNick") String schoolNick, @JsonProperty("teacherNick") String teacherNick) {
            super();
            this.teacherId = teacherId;
            this.schoolId = schoolId;
            this.schoolNick = schoolNick;
            this.teacherNick = teacherNick;
        }

        private String teacherId;
        private String schoolId;
        private String schoolNick;
        private String teacherNick;

        public String getTeacherId() {
            return teacherId;
        }

        public void setTeacherId(String teacherId) {
            this.teacherId = teacherId;
        }

        public String getSchoolId() {
            return schoolId;
        }

        public void setSchoolId(String schoolId) {
            this.schoolId = schoolId;
        }

        public String getSchoolNick() {
            return schoolNick;
        }

        public void setSchoolNick(String schoolNick) {
            this.schoolNick = schoolNick;
        }

        public String getTeacherNick() {
            return teacherNick;
        }

        public void setTeacherNick(String teacherNick) {
            this.teacherNick = teacherNick;
        }

    }
}
